<?php
function is_weixin_browser()
{
    return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== FALSE;
}

function is_valid_email($email)
{
    return !!filter_var($email, FILTER_VALIDATE_EMAIL);
}

function is_valid_password($password)
{
    return strlen($password) >= 6;
}

/**
 * 检查uname是否符合规则
 * 
 * uname须为4-20位的中文、英文、数字、下划线、中划线
 * 
 * @param string $uname
 * @return boolean
 */
function is_valid_uname($uname)
{
    static $min_length = 4;
    static $max_length = 20;
    
    /*
    $is_safe = preg_match("/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_-]+$/", $uname); // GB2312
    */
    $is_safe = preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_-]+$/u", $uname); // UTF-8
    $length  = mb_strlen($uname, 'utf-8');
    
    return $is_safe && $length >= $min_length && $length <= $max_length;
}

function is_valid_mobile($mobile)
{
    /*
     * 移动： 139   138   137   136   135   134   147   150   151   152   157   158   159   182   183   187   188
     * 联通： 130   131   132   155   156   185   186   145
     * 电信： 133   153   180   189   181
     */
    $mobile_prefixs_array = array('139', '138', '137', '136', '135', '134', '147', '150',
                                  '151', '152', '157', '158', '159', '182', '183', '187', 
                                  '188', '130', '131', '132', '155', '156', '185', '186', 
                                  '145', '133', '153', '180', '189', '181');
    $mobile_prefix = substr($mobile, 0, 3);
    return is_numeric($mobile) && strlen($mobile) == 11 && in_array($mobile_prefix, $mobile_prefixs_array);
}

function password_encode($password)
{
    return md5($password);
}

function get_page_html($total_count, $page_count = 20)
{
    import('ORG.Util.Page');
    $page = new Page($total_count, $page_count);
    return $page->show();
}

function array_shift_key($array, $key)
{
    $result = NULL;
    foreach ($array as $v) {
        $result[$v[$key]] = $v;
    }
    
    return $result;
}

function get_sub_array($array, $key)
{
    $result = NULL;
    foreach ($array as $v) {
        $result[] = $v[$key];
    }
    
    return $result;
}

function plain_string($string)
{
    import('ORG.Util.Input');
    return Input::forShow($string);
}

function safe_html($string, $allowTags = NULL)
{
    import('ORG.Util.Input');
    return Input::deleteHtmlTags($string);
}

function send_email($to_email, $subject, $body, $type = 'HTML')
{
    $from_email = '';
    $from_name  = '';
    
    vendor('SMTP.smtp');
    $smtp = new smtp("smtp.qq.com", 25, true, '', '');
    return $smtp->sendmail($to_email, $from_email, $from_name, $subject, $body, $type);
}
